#include <string.h>

#include "EString.h"

void EString::InitEString(int initLen)
{
	len = initLen;
	capacity = getCapacityByLen(len);
	buffer = new char[capacity + 1];
	memset(buffer , 0 , capacity + 1);
}

EString::EString(int initLen)
{
	InitEString(initLen);
}

EString::EString(const char* inputStr)
{
	InitEString(strlen(inputStr));
	strcpy(buffer , inputStr);
}


EString::EString(EString& ref)
{
	InitEString(ref.len);
	memcpy(this->buffer , ref.buffer , len);
}

EString::~EString(void)
{
	delete buffer;
	buffer = NULL;
	len = -1;
	capacity = -1;
}

EString& EString::operator =(EString& ref)
{
	if(this->buffer != ref.buffer)
	{
		if(this->capacity <= ref.len)
		{
			delete this->buffer;
			InitEString(ref.len);
		}
		memcpy(this->buffer , ref.buffer , ref.len);
	}
	return *this;
}

const char* EString::c_str()
{
	return this->buffer;
}

const char EString::operator [](int pos)
{
	if(pos < len)
		return buffer[pos];
	else
		return 0;
}

EString EString::operator+(EString& opEString)
{
	EString tmp(this->len + opEString.len);
	strcpy(tmp.buffer , this->buffer);
	strcat(tmp.buffer , opEString.buffer);
	return tmp;
}

ostream& operator <<(ostream& out , EString &str)
{
	out << "Len is " << str.len << " Capacity is " << str.capacity << " buffer is " << str.buffer << endl;
	return out;
}
